<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace hiduoke\services\workWechat;

use app\common\model\platform\Platform;
use app\common\model\system\Config;
use EasyWeChat\Factory;
use think\facade\Cache;

class WorkWechatOpen
{
    // 获取服务商配置
    /**
     * @var array|string[]
     */
    public array $config;

    public function getOpenConfig()
    {

        $res = (new Config())->getValueByKey("workWechat") ?? [];
        $this->config = [
            'corp_id'      => $res['corpid'] ?? '',
            'secret'       => $res['secret'] ?? '',
            'suite_id'     => $res['suite_id'] ?? '',
            'suite_secret' => $res['suite_secret'] ?? '',
            'token'        => $res['token'] ?? '',
            'aes_key'      => $res['aes_key'] ?? '',
            'log'          => [
                'default'  => 'error', // 默认使用的 channel，生产环境可以改为下面的 prod
                'channels' => [
                    'error' => [
                        'driver' => 'single',
                        'path'   => '/tmp/easywechat/work_wechat_error.log',
                        'level'  => 'error',
                    ],
                ],
            ],
        ];

        return $this->config;
    }

    // 获取服务商实例化
    public function getOpenApp()
    {
        static $app;
        if (!$app) {
            $config = $this->getOpenConfig();
            $app = Factory::openWork($config);
            return $app;
        }
        return $app;
    }

    /**
     * 获取企业授权信息
     * @return false|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getAuthorization($plaid = 0)
    {
        try {
            $plaid = $plaid ?: get_plaid();
            $platform = (new Platform())->where('plaid', $plaid)->find();
            $res = (new WorkWechatOpen())->getOpenApp()->corp->getAuthorization($platform['corp_id'], $platform['config']['permanent_code'] ?? '');
            return $res;
        } catch (\Exception $e) {
            return false;
        }
    }

}
